<template>
  <div class="cacheManage">
    <basic-container>
      <div>
        <m-s-search
          @searchClick="(v) => queryFormData(v)"
          :list="cacheManageOption.column"
        >
        </m-s-search>
      </div>
      <avue-crud
        :option="cacheManageOption"
        :data="data"
        :table-loading="loading"
        :page.sync="page"
        @current-change="currentChange"
        @size-change="sizeChange"
        @selection-change="(v) => (selection = v)"
        ref="curd"
      >
        <template slot="menuLeft">
          <el-button size="small" type="default" @click="goBack"
            >返回
          </el-button>

          <el-button size="small" @click="clearCache">删除 </el-button>
        </template>
        <template slot="menu" slot-scope="{ row }">
          <el-button type="text" @click="showDialog(row)"> 编辑 </el-button>
          <el-button type="text" @click="deleteRow(row)"> 删除 </el-button>
        </template>
      </avue-crud>
      <el-dialog
        :visible.sync="dialogVisible"
        :before-close="beforeClose"
        append-to-body
        title="编辑"
        width="850px"
      >
        <el-form
          ref="dialogForm"
          :model="dialogForm"
          :rules="dialogRules"
          label-width="80px"
        >
          <el-form-item label="数据类型">
            <el-select
              v-model="dialogForm.dataType"
              style="width: 100px"
              disabled
            >
              <el-option
                v-for="item in redisTypeList"
                :key="item.name"
                :label="item.name"
                :value="item.name"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="键" prop="redisKey">
            <el-input
              style="width: 470px"
              v-model="dialogForm.redisKey"
              placeholder="redisKey"
            ></el-input>
            <el-button
              type="primary"
              style="margin-left: 10px"
              @click="updateKey"
              >更新名称</el-button
            >
          </el-form-item>
          <el-form-item label="过期时间(旧)">
            <div>{{ dialogForm.expire }}</div></el-form-item
          >
          <el-form-item label="过期时间(新)">
            <el-input
              style="width: 260px"
              v-model="dialogForm.expireNumber"
              placeholder="expire"
            ></el-input>
            <el-select
              v-model="dialogForm.unit"
              style="width: 200px; margin-left: 10px"
            >
              <el-option
                v-for="item in timeList"
                :key="item.value"
                :label="item.name"
                :value="item.value"
              ></el-option>
            </el-select>
            <el-button
              type="primary"
              style="margin-left: 10px"
              @click="updateTime"
              >更新过期时间</el-button
            >
            <div>只能输入正整数/负数，任意附属代表用不过期，输0则无效</div>
          </el-form-item>
          <el-form-item label="值" prop="redisValue">
            <el-input
              type="textarea"
              :rows="5"
              placeholder="请输入内容"
              v-model="dialogForm.redisValue"
              style="width: 470px"
            >
            </el-input>
            <el-button
              type="primary"
              style="margin-left: 10px"
              @click="updateValue"
              >更新值</el-button
            >
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="beforeClose">取 消</el-button>
        </span>
      </el-dialog>
    </basic-container>
  </div>
</template>
<script>
import commonJs from "@/util/commonJs";
import MSSearch from "@/DMDComponents/MSSearch.vue";
import * as api from "@/api/cacheManage/cacheManage";
import * as common from "@/api/common";

export default {
  name: "cacheManage",
  mixins: [commonJs],
  inject: ["cacheManageOption"],
  components: { MSSearch },
  data() {
    return {
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      loading: false,
      dialogVisible: false,
      queryForm: {},
      data: [],
      selection: [],
      redisTypeList: [], //数据类型
      timeList: [], //数据类型
      dialogForm: {},
      currentData: {},
      redisGroup: "",
      dialogRules: {
        redisKey: { required: true, message: "请输入键值" },
        redisValue: { required: true, message: "请输入值" },
      },
    };
  },
  watch: {
    "$route.query": {
      handler(val) {
        if (val && val.key) {
          this.redisGroup = val.key;
          this.getList();
        }
      },
      immediate: true,
    },
  },
  mounted() {
    this.getEnumData();
  },
  methods: {
    clearCache() {
      if (this.selection.length === 0) {
        this.$message.error("请先选择！");
        return;
      }
      const listData = this.selection.map((row) => ({
        dataType: row.dataType,
        redisKey: row.redisKey,
      }));
      this.$confirm("确认删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          api.delKey(listData).then((res) => {
            this.$message.success("删除成功！");
            this.queryFormData();
          });
        })
        .catch(() => {});
    },
    updateKey() {
      const { redisKey, dataType } = this.dialogForm;
      if (!redisKey) {
        this.$message.error("请输入键名称！");
        return;
      }
      api
        .updateKeyName({
          redisKey,
          dataType,
          oldRedisKey: this.currentData.redisKey,
        })
        .then((res) => {
          if (res.data.success) {
            this.$message.success("更新键成功！");
          } else {
            this.$message.success("更新键失败！");
          }
        });
    },
    updateTime() {
      const { redisKey, dataType, unit, expireNumber } = this.dialogForm;
      if (!unit || !expireNumber) {
        this.$message.error("请输入时间！");
        return;
      }
      const regN = /^-?[1-9]\d*$/;
      if (!regN.test(expireNumber)) {
        this.$message.error("时间只可为整数！");
        return;
      }
      api
        .updateKeyTime({ redisKey, dataType, unit, expire: expireNumber })
        .then((res) => {
          if (res.data.success) {
            this.$message.success("更新时间成功！");
          } else {
            this.$message.success("更新时间失败！");
          }
        });
    },
    updateValue() {
      const { redisKey, dataType, redisValue } = this.dialogForm;
      if (!redisValue) {
        this.$message.error("请输入值！");
        return;
      }
      api.updateKeyValue({ redisKey, dataType, redisValue }).then((res) => {
        if (res.data.success) {
          this.$message.success("更新值成功！");
        } else {
          this.$message.success("更新值失败！");
        }
      });
    },
    getEnumData() {
      common.getDic("redis_type").then((res) => {
        this.redisTypeList = res.data.data;
      });
      common.getDic("redis_time_unit").then((res) => {
        this.timeList = res.data.data;
      });
    },
    showDialog(row) {
      api
        .cacheDetail({ dataType: row.dataType, redisKey: row.redisKey })
        .then((res) => {
          const detailData = res.data.data;
          this.dialogForm = { ...detailData, unit: "SECONDS" };
          this.currentData = { ...detailData };
          this.dialogVisible = true;
        });
    },
    beforeClose() {
      this.dialogVisible = false;
      this.getList();
    },
    goBack() {
      this.$router.push({ path: "/cacheManage/cacheManageGroup" });
    },
    deleteRow(row) {
      this.$confirm("确认删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          api
            .delKey([{ dataType: row.dataType, redisKey: row.redisKey }])
            .then((res) => {
              this.$message.success("删除成功！");
              this.queryFormData();
            });
        })
        .catch(() => {});
    },
    initPage() {
      this.page = {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      };
    },
    queryFormData(v) {
      if (v) {
        this.queryForm = v;
      }
      this.initPage();
      this.getList();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
      this.getList();
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
      this.getList();
    },
    getList() {
      this.loading = true;
      if(!this.redisGroup){
        return
      }
      api
        .getKeyList({
          current: this.page.currentPage,
          size: this.page.pageSize,
          redisGroup: this.redisGroup,
          ...this.queryForm,
        })
        .then((res) => {
          const { list, totalRows } = res.data.data;
          this.page.total = totalRows;
          this.data = list;
          this.loading = false;
        });
    },
  },
};
</script>